// <copyright file="PPIDGeneratorProviderManager.cs" company="SharpSTS">
// Copyright (c) 2007, 2008 All Right Reserved, http://sharpsts.com/
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Barry Dorrans</author>
// <email>barryd@idunno.org</email>
// <date>2008-06-14</date>
// <summary>Provides access to the PPID Generator provider.</summary>

namespace SharpSTS.Providers
{
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.Security.Cryptography;
    using System.ServiceModel;
    using System.Web.Configuration;    
    
    using Configuration;

    /// <summary>
    /// The entry point to the provider model for validating endpoints.
    /// </summary>
    internal static class PPIDGeneratorProviderManager
    {
        /// <summary>
        /// Lookup table for PPID encoding symbols.
        /// </summary>
        private static readonly char[] encodedSymbol =
            {
                'Q', 
                'L', 
                '2', 
                '3', 
                '4', 
                '5', 
                '6', 
                '7', 
                '8', 
                '9', 
                'A', 
                'B', 
                'C', 
                'D', 
                'E', 
                'F', 
                'G', 
                'H', 
                'J', 
                'K', 
                'M',
                'N', 
                'P', 
                'R', 
                'S', 
                'T', 
                'U', 
                'V', 
                'W', 
                'X', 
                'Y', 
                'Z'
            };

        /// <summary>
        /// Provides a syncronisation object for thread safe provider loading.
        /// </summary>
        private static readonly object syncRoot = new object();

        /// <summary>
        /// The selected <see cref="PPIDGeneratorProvider"/>.
        /// </summary>
        private static PPIDGeneratorProvider provider;

        /// <summary>
        /// Gets the provider.
        /// </summary>
        /// <value>The provider.</value>
        private static PPIDGeneratorProvider Provider
        {
            get
            {
                LoadProviders();
                return provider;
            }
        }

        /// <summary>
        /// Gets the PPID.
        /// </summary>
        /// <param name="cardId">The card identifier for the current request</param>
        /// <param name="endpoint">The relaying party <see cref="EndpointAddress"/>.</param>
        /// <param name="selectorSuggestedPPID">The selector suggested PPID.</param>
        /// <returns>A PPID for the card identifier and endpoint address.</returns>
        public static string GetPPID(string cardId, EndpointAddress endpoint, string selectorSuggestedPPID)
        {
            return Provider.GetPPID(cardId, endpoint, selectorSuggestedPPID);
        }

        /// <summary>
        /// Gets a suitable friendly identifier for a display token.
        /// </summary>
        /// <param name="ppid">The PPID to generate the display value from.</param>
        /// <returns>A suitable PPID friendly identifier.</returns>
        public static string GetFriendlyIdentifier(string ppid)
        {
            byte[] ppidBytes = Convert.FromBase64String(ppid);

            SHA1 sha = new SHA1Managed();
            byte[] hashId = sha.ComputeHash(ppidBytes);

            return (
                string.Format(
                  CultureInfo.InvariantCulture,
                  "{0}{1}{2}-{3}{4}{5}{6}-{7}{8}{9}",
                  ConvertOctetToEncodedSymbol(hashId[0]),
                  ConvertOctetToEncodedSymbol(hashId[1]),
                  ConvertOctetToEncodedSymbol(hashId[2]),
                  ConvertOctetToEncodedSymbol(hashId[3]),
                  ConvertOctetToEncodedSymbol(hashId[4]),
                  ConvertOctetToEncodedSymbol(hashId[5]),
                  ConvertOctetToEncodedSymbol(hashId[6]),
                  ConvertOctetToEncodedSymbol(hashId[7]),
                  ConvertOctetToEncodedSymbol(hashId[8]),
                  ConvertOctetToEncodedSymbol(hashId[9])));
        }

        /// <summary>
        /// Converts the octet to encoded symbol.
        /// </summary>
        /// <param name="octet">The octet to encode.</param>
        /// <returns>The encoded symbol for the specified octet.</returns>
        private static char ConvertOctetToEncodedSymbol(byte octet)
        {
            return encodedSymbol[Convert.ToInt16(octet % 32)];
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private static void LoadProviders()
        {
            if (null != provider)
            {
                return;
            }

            lock (syncRoot)
            {
                if (null != provider)
                {
                    return;
                }

                string providerSectionPath =
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{0}/{1}",
                        ProvidersSectionGroup.ConfigurationSectionGroupName,
                        PPIDGeneratorProviderSection.ConfigurationSectionName);
                PPIDGeneratorProviderSection section =
                    (PPIDGeneratorProviderSection)
                    ConfigurationManager.GetSection(providerSectionPath);

                PPIDGeneratorProviderCollection providers = new PPIDGeneratorProviderCollection();
                ProvidersHelper.InstantiateProviders(section.Providers, providers, typeof(PPIDGeneratorProvider));
                provider = providers[section.DefaultProvider];
            }
        }
    }
}
